package com.bw.a2207a.view

import android.content.Intent
import android.text.TextUtils
import android.view.View
import android.view.View.OnClickListener
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.bw.a2207a.R
import com.bw.a2207a.base.BaseActivity2
import com.bw.a2207a.databinding.ActivityLoginBinding
import com.bw.a2207a.viewmodel.LoginViewModel
import com.tencent.mm.opensdk.modelmsg.SendAuth
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch


class LoginFlowActivity : BaseActivity2<ActivityLoginBinding, LoginViewModel>(
    R.layout.activity_login,
    LoginViewModel()
) {
    override fun initData() {
        viewModel.loginLiveData.observe(this) {
        }

        //通过lifecycleScope，开启协程，接收loginFlowData数据
        lifecycleScope.launch {
            viewModel.loginFlowData.collect() {
                ToastUtils.showShort(it.message)
                if (it.code == 200) {
                    SPUtils.getInstance().put("token", it.data.token)
                    startActivity(Intent(this@LoginFlowActivity, MainActivity::class.java))
                    finish()
                }
            }
        }

    }

    override fun initView() {
        val name = intent.getStringExtra("name")
        val pass = intent.getStringExtra("pass")

        if (!TextUtils.isEmpty(name)) {
            binding.etUsername.setText(name)
        }
        if (!TextUtils.isEmpty(pass)) {
            binding.etPassword.setText(pass)
        }

        binding.btn.setOnClickListener {
            val name = binding.etUsername.text.toString()
            val pass = binding.etPassword.text.toString()

            if (TextUtils.isEmpty(name) || TextUtils.isEmpty(pass)) {
                ToastUtils.showShort("请输入用户名或密码")
                return@setOnClickListener
            }

            //声明参数变量 map
            val map = HashMap<String, String>()
            map.put("username", name)
            map["password"] = pass

            //发起网络请求
            // viewModel.login(map)

        }

        binding.tvRegister.setOnClickListener { //跳转到注册页面
            val intent = Intent(this@LoginFlowActivity, RegisterActivity::class.java)
            startActivity(intent)
        }
    }


}